package com.base.helper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;
import java.util.Map;

import com.base.po.union.BaseHttpSSLSocketFactory;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;

import com.base.utils.Produce;

import javax.net.ssl.*;

public class WebHelper {

	/**
	 * 处理HTTPGET请求
	 *
	 * @param httpurl
	 * @return
     */
	public static String GetData(String httpurl, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = null;
			if (param != null) {
				urlNameString = httpurl + "?" + param;
			} else {
				urlNameString = httpurl;
			}
			System.out.println("访问URL"+urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// }
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		// System.out.println(new String(result.getBytes(), "UTF-8"));
		return result;
	}
	/**
	 * 处理HTTPPOST请求
	 *
	 * @param httpUrl
	 * @param param
	 * @return
	 */
	public static String PostData(String httpUrl, String param, String ContentType, String token) {
		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream os = null;
		BufferedReader br = null;
		String result = null;
		try {
			URL url = new URL(httpUrl);
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取主机服务器返回数据超时时间：60000毫秒
			connection.setReadTimeout(60000);
			// 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
			connection.setDoOutput(true);
			// 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
			connection.setDoInput(true);

			connection.setInstanceFollowRedirects(false);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			// 可控返回参数默认 application/x-www-form-urlencoded
			if (ContentType == null) {
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			} else {
				connection.setRequestProperty("Content-Type", ContentType);
			}
			// 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
			if (token != null) {
				connection.setRequestProperty("Authorization", token);
			}
			// 通过连接对象获取一个输出流
			os = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			if (param != null) {
				os.write(param.getBytes(StandardCharsets.UTF_8));
			}

			// 通过连接对象获取一个输入流，向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}else{
				String redirectUrl = connection.getHeaderField("Location");
				if(redirectUrl != null && !redirectUrl.isEmpty()) {
					String urls = redirectUrl;

					System.out.println(urls);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		return result;
	}
	/**
	 * 处理HTTPPOST请求，带请求头
	 *
	 * @param httpUrl
	 * @param param
	 * @return
	 */
	public static String PostDataHeader(String httpUrl, String param, String ContentType, String token,String HeaderName,String HeaderString) throws MalformedURLException, KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
		SSLContext sslcontext = SSLContext.getInstance("SSL","SunJSSE");
		sslcontext.init(null, new TrustManager[]{new BaseHttpSSLSocketFactory.MyX509TrustManager()}, new java.security.SecureRandom());
		URL url = new URL(httpUrl);
		HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
			public boolean verify(String s, SSLSession sslsession) {
				System.out.println("WARNING: Hostname is not matched for cert.");
				return true;
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
		HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream os = null;
		BufferedReader br = null;
		String result = null;
		try {
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取主机服务器返回数据超时时间：60000毫秒
			connection.setReadTimeout(60000);
			// 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
			connection.setDoOutput(true);
			// 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
			connection.setDoInput(true);

			connection.setInstanceFollowRedirects(false);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			// 可控返回参数默认 application/x-www-form-urlencoded
			if (ContentType == null) {
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			} else {
				connection.setRequestProperty("Content-Type", ContentType);
			}
			// 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
			if (token != null) {
				connection.setRequestProperty("Authorization", token);
			}
			if (HeaderName!=null){
				connection.setRequestProperty(HeaderName, HeaderString);
			}
			// 通过连接对象获取一个输出流
			os = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			if (param != null) {
				os.write(param.getBytes(StandardCharsets.UTF_8));
			}

			// 通过连接对象获取一个输入流，向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}else{
				String redirectUrl = connection.getHeaderField("Location");
				if(redirectUrl != null && !redirectUrl.isEmpty()) {
					String urls = redirectUrl;

					System.out.println(urls);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		return result;
	}

	/**
	 * post请求
	 *
	 * @param url
	 * @param json
	 * @return
	 */
	public static String doPost(String url, String json, String contentType) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		String response = null;
		try {
			StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
			s.setContentEncoding("UTF-8");
			if (contentType != null) {
				s.setContentType(contentType);
			} else {
				s.setContentType("application/json");// 发送json数据需要设置contentType
			}
			post.setEntity(s);
			HttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = res.getEntity();
				response = EntityUtils.toString(res.getEntity());// 返回json格式：
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
//		System.out.println(response);
		return response.trim();
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setRequestProperty("Charset", "UTF-8");

			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String doBodyPost(String strURL, JSONObject params) {
		String response = null;
		// 客户端接口请求路径
//		String url = EspConfig.getClientBaseUrl() + ClientUtil.CLIENT_METHODNAME;
		// 创建请求
		CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

		HttpPost post = new HttpPost(strURL);
		// 配置请求
		post.setHeader("Content-Type", "application/json;charset=UTF-8;");
		StringEntity stringEntity = new StringEntity(params.toString(), "utf-8");
		stringEntity.setContentEncoding("utf-8");
		stringEntity.setContentType("application/json");
		post.setEntity(stringEntity);
		System.out.println(post.toString());
		System.out.println(stringEntity.getContentLength());
		try {
		    // 执行请求获取响应
		    HttpResponse res = httpClient.execute(post);
//		    if (res.getStatusLine().getStatusCode() == 200) {
		       response = EntityUtils.toString(res.getEntity());
//		    }
		    //判断返回是否为空
		    if(response == null){
		      throw new NullPointerException("推送异常");
		    }
		} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		}

		return response;
	}

	public static String doBodyPostFJ(String strURL, com.alibaba.fastjson.JSONObject params) {
		String response = null;
		// 客户端接口请求路径
//		String url = EspConfig.getClientBaseUrl() + ClientUtil.CLIENT_METHODNAME;
		// 创建请求
		CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

		HttpPost post = new HttpPost(strURL);
		// 配置请求
		post.setHeader("Content-Type", "application/json;charset=UTF-8;");
		StringEntity stringEntity = new StringEntity(params.toString(), "utf-8");
		stringEntity.setContentEncoding("utf-8");
		stringEntity.setContentType("application/json");
		post.setEntity(stringEntity);
//		System.out.println(post.toString());
//		System.out.println(stringEntity.getContentLength());
		try {
			// 执行请求获取响应
			HttpResponse res = httpClient.execute(post);
//		    if (res.getStatusLine().getStatusCode() == 200) {
			response = EntityUtils.toString(res.getEntity());
//		    }
			//判断返回是否为空
			if(response == null){
				throw new NullPointerException("推送异常");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return response;
	}

	/**
	 * post请求
	 *
	 * @param url
	 * @param json
	 * @return
	 */
	public static String doPost(String url, String json) {
		return doPost(url, json, null);
	}

	public static void main(String[] args) {
		// String data = "{\"callerE164\":\"" + "15168269848" +
		// "\",\"calleeE164s\":\"" + "18815264616"
		// + "\",\"accessE164\":\"19989\",\"accessE164Password\":\"IPZXOcFE\"}";
		// String s = VosHelper.VosCallBack(data);
		// String tokendata =
		// "{\"Username\":\"20151\",\"Password\":\"B6dfOt3GaNuouyt8mBrZ1BTQqoIQl02A\"}";
		// String tokenresult =
		// WebHelper.PostData("http://118.31.238.194:8088/api/login",
		// tokendata, "application/json",
		// null);
		// String token = "JH
		// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjU3NTQyMjAsImlkIjoiMjAxNTEiLCJvcmlnX2lhdCI6MTUyNTY2NzgyMH0.thCanEHXfZSMeGEshQSO3nUwpTNZKdRh1qj1XePzrTM";
		// String datas = "{\"Callid\":\"" + Produce.getUUID()
		// +
		// "\",\"App_id\":\"20151\",\"Appkey\":\"B6dfOt3GaNuouyt8mBrZ1BTQqoIQl02A\",\"Caller\":\""
		// + "15168269848" + "\",\"Callee\":\"" + "18815264616"
		// + "\",\"Cdr_url\":\"http://admin.xsroem.com/Vm9pcEFwaQ/OSDIHF\"}";
		// String callresult =
		// WebHelper.PostData("http://118.31.238.194:8088/api/CallRequest",
		// datas,
		// "application/json", token);
		//String token = "JH " + JHHelper.getRedis();// 获取TOKEN
		//String a = JHHelper.bh("15168269848", "18815264616", token, Produce.getUUID());
		//System.out.println(a);
		// 发送 GET 请求
		// String s = doGet("http://www.baidu.com", "");
		// System.out.println("doGet:" + s);
		//
		// // 发送 POST 请求
		// String sr = doPost("http://www.baidu.com", "key=123&v=456");
		// System.out.println("doPost:" + sr);
	}

}
